const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const bcrypt = require('bcryptjs');
const Role = require('./role');

const User = sequelize.define('User', {
    name: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
            isValidName(value) {
                if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(value)) {
                    throw new Error('用户名必须以字母开头，且只能包含字母和数字');
                }
            }
        }
    },
    age: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
            isEmail: true
        }
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false
    }
});

// 密码加密中间件
User.beforeCreate(async (user) => {
    const salt = await bcrypt.genSalt(10);
    user.password = await bcrypt.hash(user.password, salt);
});

// 建立用户和角色的关联关系
User.belongsTo(Role, {
    foreignKey: {
        name: 'roleId',
        allowNull: false,
        defaultValue: 2  // 默认为普通用户角色
    }
});
Role.hasMany(User, {
    foreignKey: 'roleId'
});

module.exports = User; 